package org.example.top40;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class main39 {
    //二叉树的右视图
    //思路：只有i==size-1时才加入集合中，即 每一次队列的最后一个
    public static void main(String[] args) {
        TreeNode root = builder();
        List<Integer> res= rightSideView(root);
        System.out.println(res);
    }

    private static List<Integer> rightSideView(TreeNode root) {
        Deque<TreeNode> dq=new LinkedList<>();
        List<Integer> res=new ArrayList<>();
        //必须加
        if (root == null) {
            return res;
        }
        dq.addLast(root);
        while (!dq.isEmpty()){
            int size = dq.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = dq.removeFirst();
                if(node.left!=null){
                    dq.addLast(node.left);
                }
                if(node.right!=null){
                    dq.addLast(node.right);
                }
                if(i==size-1){
                    res.add(node.val);
                }
            }
        }
        return res;
    }

    private static TreeNode builder(){
        TreeNode root = new TreeNode(3);
        TreeNode node1 = new TreeNode(9);
        TreeNode node2 = new TreeNode(20);
        TreeNode node3 = new TreeNode(15);
        TreeNode node4 = new TreeNode(7);
        root.left=node1;
        root.right=node2;
        node2.left=node3;
        node2.right=node4;
        return root;
    }
}
